<?php
// +----------------------------------------------------------------------
// | UCToo [ Universal Convergence Technology ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014-2021 https://www.uctoo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Patrick <contact@uctoo.com>
// +----------------------------------------------------------------------

namespace uctoo\util\EventHandler\openPlatform;


use EasyWeChat\Kernel\Contracts\EventHandlerInterface;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\OpenPlatform\Application;

class FullPublicMessageHandler implements EventHandlerInterface
{

    /**
     * @var Application $app
     */
    protected $app;
    protected $method;
    protected $appid;

    public function __construct($app,$appid,$method)
    {
        $this->app = $app;
        $this->appid = $appid;
        $this->method = $method;
    }

    public function handle($payload = null)
    {
        if ('TESTCOMPONENT_MSG_TYPE_TEXT' === $payload['Content']) {
            return new Text('TESTCOMPONENT_MSG_TYPE_TEXT_callback');
        }elseif(false != strpos('QUERY_AUTH_CODE:',$payload['Content'])){
            $query_auth_code = str_replace('QUERY_AUTH_CODE:','',$payload['Content']);
            $authInfo = $this->app->handleAuthorize($query_auth_code);
            $refresh_token = $authInfo['authorization_info']['authorizer_refresh_token'] ?? '';
            /**
             * @var \EasyWeChat\OfficialAccount\Application|\EasyWeChat\MiniProgram\Application $app
             */
            $app = $this->app->{$this->method}($this->appid,$refresh_token);
            $app->customer_service->message(new Text($query_auth_code.'_from_api'))->to($payload['FromUserName'])->send();
            return '';
        }
    }
}